#include "bsp_gpio.h"

static GPIOInstance* GPIO_Instance_List[GPIO_MAX_NUM] = {NULL};
static uint8_t Idx = 0;

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
    GPIOInstance* gpio = NULL;
    for (uint8_t i = 0; i < GPIO_MAX_NUM; i++)
    {
        gpio = GPIO_Instance_List[i];
        if(GPIO_Pin == gpio -> GPIO_Pin 
        && NULL != gpio -> gpio_exti_callback) 
        {
            gpio -> gpio_exti_callback(gpio);
            break;
        }
    }
}
GPIOInstance* GPIOInit(GPIO_Init_Config_s* _config) 
{
    GPIOInstance* instance = (GPIOInstance*)malloc(sizeof(GPIOInstance));
    memset(instance, 0, sizeof(GPIOInstance));

    instance -> GPIOx = _config -> GPIOx;
    instance -> GPIO_Pin = _config -> GPIO_Pin;
    instance -> Pin_State = _config -> Pin_State;
    instance -> EXTI_Mode = _config -> EXTI_Mode;
    instance -> gpio_exti_callback = _config -> gpio_exti_callback;
    instance -> id = _config -> id;
	GPIO_Instance_List[Idx ++] = instance;
    return instance;
}

void GPIOToggle(GPIOInstance* _instance) 
{
    HAL_GPIO_TogglePin(_instance -> GPIOx, _instance -> GPIO_Pin);
}

void GPIOSet(GPIOInstance* _instance) 
{
    HAL_GPIO_WritePin(_instance -> GPIOx, _instance -> GPIO_Pin, GPIO_PIN_SET);
}

void GPIOReset(GPIOInstance* _instance) 
{
    HAL_GPIO_WritePin(_instance -> GPIOx, _instance -> GPIO_Pin, GPIO_PIN_RESET);
}

GPIO_PinState GPIORead(GPIOInstance* _instance)
{
    return HAL_GPIO_ReadPin(_instance -> GPIOx, _instance -> GPIO_Pin);
}
